<?php

namespace App\Models\Train\TrainIssues;

use App\Models\Train\TrainOrders\Repositories\Interfaces\TrainOrdersRepositoryInterface;
use App\Models\Trip\TripOrderCosts\TripOrderCost;
use App\Trip\Orders\TripOrderState;
use App\Trip\Train\Seat\SeatName;
use App\Trip\Traits\ModelDateTrait;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

//use Jenssegers\Mongodb\Eloquent\Model;

/**
 * App\Models\Train\TrainIssues\TrainIssue
 *
 * @property int         $id
 * @property int         $issue_id
 * @property string      $title      问题
 * @property string      $title_uy   问题维语
 * @property string      $content    问题内容
 * @property string      $content_uy 问题内容维语
 * @property string      $image      图片地址
 * @property int         $dynamic    数据是否为动态，1 动态 0 非动态原样输出
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @method static Builder|TrainIssue newModelQuery()
 * @method static Builder|TrainIssue newQuery()
 * @method static Builder|TrainIssue query()
 * @method static Builder|TrainIssue whereContent($value)
 * @method static Builder|TrainIssue whereContentUy($value)
 * @method static Builder|TrainIssue whereCreatedAt($value)
 * @method static Builder|TrainIssue whereDynamic($value)
 * @method static Builder|TrainIssue whereId($value)
 * @method static Builder|TrainIssue whereImage($value)
 * @method static Builder|TrainIssue whereIssueId($value)
 * @method static Builder|TrainIssue whereTitle($value)
 * @method static Builder|TrainIssue whereTitleUy($value)
 * @method static Builder|TrainIssue whereUpdatedAt($value)
 * @mixin Eloquent
 */
class TrainIssue extends Model
{
    use ModelDateTrait;

//	protected $connection = 'mongodb';
//	protected $collection = 'train_issues';
    protected $table = 'train_issues';
    protected $fillable
                     = [
            "issue_id",
            "title",
            "title_uy",
            "content",
            "content_uy",
            "image",
            "dynamic",
        ];

    protected $hidden
        = [
            'dynamic',
            'id',
            'created_at',
            'updated_at',
        ];

    public function addIssue($data)
    {
        $data['dynamic'] = ($data['dynamic'] ?? 0) == 1 ? 1 : 0;
        if (isset($data['issue_id'])) {
            $issue = $this->findByIssueId($data['issue_id']);
        } else {
            $issue = $this->findByTitle($data['title']);
        }
        DB::transaction(function () use ($data, $issue) {
            if ($issue) {
                $issue->update($data);
            } else {
                $issue = $this->create($data);
            }
            // 同步更新
            $r = new TrainIssueRelation();
            if (isset($data['order_state']) && $data['order_state'] >= 0) {
                $r->addRelation($issue, $data['order_state']);
            }

            if (isset($data['order_states']) && !empty($data['order_states'])) {
                foreach ($data['order_states'] as $state) {
                    $r->addRelation($issue, $state);
                }
            }
        });

        return $issue;
    }

    public function findByIssueId($issue_id)
    {
        $cache_key = "Issue:issue_id:{$issue_id}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $res = $this->where('issue_id', $issue_id)->first();
        if ($res) {
            Cache::put($cache_key, $res, config('trip.ttl.day') * 10);
        }
        return $res;
    }

    public function findByTitle(string $title)
    {
        $cache_key = "Issue:title:{$title}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $res = $this->where('title', $title)->first();
        if ($res) {
            Cache::put($cache_key, $res, config('trip.ttl.day') * 10);
        }
        return $res;
    }

    public function findById($id)
    {
        $cache_key = "Issue:id:{$id}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $res = $this->find($id);
        if ($res) {
            Cache::put($cache_key, $res, config('trip.ttl.day') * 10);
        }
        return $res;
    }

    public function getId()
    {
        return $this->getAttribute($this->primaryKey);
    }

    public function getIssueId()
    {
        return $this->getAttribute('issue_id');
    }

    public function listIssue(int $order_state, string $order_sn = '')
    {
        $trainOrderRepo = app(TrainOrdersRepositoryInterface::class);
        $r              = new TrainIssueRelation();
        $train_order    = $order_sn ? $trainOrderRepo->getOrderInfo($order_sn) : null;
        if ($train_order && $train_order->isSnapUp() && TripOrderState::canReplaceSnapState($train_order->getOrderState())) {
            $order_state = $train_order->getOrderSnapState();
        }
        $ids  = $r->getIssueIdsByOrderState($order_state);
        $list = $this
            ->whereIn('issue_id', $ids)
            ->get();

        return collect($list)
            ->filter(function ($issue) use ($order_sn) {
                if ($issue['title'] == "我的订单支付明细" && !$order_sn) {
                    return false;
                }
                return true;
            })->map(function ($issue) use ($train_order) {
                if ($issue['title'] == "我的订单支付明细" && $train_order) {
                    $costs   = $train_order->getPriceDetails();
                    $content = $issue['content'];
                    if (!empty($costs) && Str::contains($content, ['[', ']', '$'])) {
                        $str         = "您的车票信息如下：";
                        $str_uy      = trans2uy("您的车票信息如下：");
                        $trip        = $costs['trips'][$train_order->getTripNo() - 1];
                        $total_price = $trip['total_price'];
                        foreach ($trip['details'] as $detail) {
                            $str .= $detail['name'];
                            $str .= $detail['detail'] ?? '';
                            $str .= sprintf("%.2f", $detail['price']);
                            $str .= "元";
                            $str .= "x";
                            $str .= $detail['count'];
                            isset($detail['type']) && $str .= TripOrderCost::COST_TYPE_UNIT[$detail['type']].",";
                            // 维语
                            $str_uy .= $detail['name_uy'];
                            $str_uy .= ($detail['type'] ?? 0) == 1 ? SeatName::trans($detail['detail'] ?? '', 'uy') : trans2uy($detail['detail'] ?? '');
                            $str_uy .= sprintf("%.2f", $detail['price']);
                            $str_uy .= trans2uy("元");
                            $str_uy .= "×";
                            $str_uy .= $detail['count'];
                            isset($detail['type']) && $str_uy .= trans2uy(TripOrderCost::COST_TYPE_UNIT[$detail['type']])."";
                        }
                        $str    .= "总支付金额";
                        $str    .= sprintf("%.2f", $total_price);
                        $str    .= "元";
                        $str_uy .= trans2uy("总支付金额");
                        $str_uy .= sprintf("%.2f", $total_price);
                        $str_uy .= trans2uy("元");

                        $issue['content']    = $str;
                        $issue['content_uy'] = $str_uy;
                    }


                }
                return $issue;
            });

    }
}
